﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;

namespace MsTestUtilities.Utilities
{
    public static class Require
    {
        public static void ArgumentNotNull(object argument, string argumentName)
        {
            if (argument == null)
            {
                throw new ArgumentNullException(argumentName);
            }
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void ArgumentNotNull<T>(T argument)
            where T : class
        {
            if (argument == null)
            {
                var caller = new StackFrame(1, true).GetMethod();

                 var matchingArguments = caller.GetParameters()
                    .Where(p => p.ParameterType == typeof(T))
                    .Select(p => p.Name)
                    .ToList();

                if (matchingArguments.Count > 1)
                {
                    var message = string.Format(
                        "Value cannot be null. Due to type collisions the actual argument could not be determined. Candidates are <{0}>.", 
                        string.Join(", ", matchingArguments));
                    throw new ArgumentNullException("Unknown", message);
                }

                throw new ArgumentNullException(matchingArguments.First());
            }
        }
    }
}
